import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('@/components/Login')
const Home = () => import('@/components/Home')
const welcome = () => import('@/components/Welcome.vue')
const users = () => import('@/components/user/Users.vue')
const rights = () => import('@/components/power/Rights.vue')
const roles = () => import('@/components/power/Roles.vue')
const categories = () => import('@/components/goods/Categories.vue')
const params = () => import('@/components/goods/Params.vue')
const list = () => import('@/components/goods/List.vue')
const add = () => import('@/components/goods/Add.vue')
const orders = () => import('@/components/order/Order.vue')
const report = () => import('../components/report/Report.vue')
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: welcome
      },
      {
        path: '/users',
        component: users
      },
      {
        path: '/rights',
        component: rights
      },
      {
        path: '/roles',
        component: roles
      },
      {
        path: '/categories',
        component: categories
      },
      {
        path: '/params',
        component: params
      },
      {
        path: '/goods',
        component: list
      },
      {
        path: '/goods/add',
        component: add
      },
      {
        path: '/orders',
        component: orders
      },
      {
        path: '/reports',
        component: report
      }
    ]
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数表示放行
  // next()放行 next('/login') 强制跳转
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  if (!tokenStr)
    return next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  next()
})
export default router
